package chapter1113;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class DrawRotate extends JPanel {

    private double angle = 0; // 旋转角度
    private final double RADIUS = 100; // 线条的长度
    private final Point center = new Point(150, 150); // 旋转中心点

    public DrawRotate() {
        Timer timer = new Timer(50, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                angle += 0.1; // 每次旋转的角度
                repaint(); // 重新绘制
            }
        });
        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 保存当前状态
        AffineTransform oldTransform = g2d.getTransform();

        // 移动到旋转中心
        g2d.translate(center.x, center.y);

        // 旋转画布
        g2d.rotate(angle);

        // 绘制线条
        g2d.drawLine(0, 0, (int) RADIUS, 0);

        // 恢复原来的状态
        g2d.setTransform(oldTransform);

        // 绘制中心点以便观察
        g2d.setColor(Color.RED);
        g2d.fillOval(center.x - 3, center.y - 3, 6, 6);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Rotating Line");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new DrawRotate());
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}